package com.usts2022.classcostrecord;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.usts2022.classcostrecord.Utils.DateFormat;
import com.usts2022.classcostrecord.Utils.HttpUtils;
import com.usts2022.classcostrecord.entity.Answer;
import com.usts2022.classcostrecord.entity.QToU;
import com.usts2022.classcostrecord.entity.Question;
import com.usts2022.classcostrecord.entity.Report;
import com.usts2022.classcostrecord.entity.User;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class AnswerFragment extends Fragment {

    private static final String ARG_QUESTION = "ARG_QUESTION";
    private static final String ARG_USER = "param2";

    private Question mQuestion;
    private User mUser;
    private List<Answer> answerList;
    private RecyclerView mRecyclerView;
    private OrderListAdapter mAdapter;
    private TextView questionContent;
    private Button answerQuestion,confirmButton;

    public static AnswerFragment newInstance(Question question, User user) {
        AnswerFragment fragment = new AnswerFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_QUESTION, question);
        args.putSerializable(ARG_USER, user);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mQuestion = (Question) getArguments().getSerializable(ARG_QUESTION);
            mUser = (User) getArguments().getSerializable(ARG_USER);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_answer, container, false);
        mRecyclerView = view.findViewById(R.id.re_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //绑定
        questionContent = view.findViewById(R.id.question_content);
        answerQuestion = view.findViewById(R.id.answerQuestion);
        confirmButton = view.findViewById(R.id.confirm_button);
        //更新UI
        try {
            updateUI();
        } catch (IOException e) {
            e.printStackTrace();
        }


        //点击确认质疑
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String postUrl = "/user/confirmAnswer";
                QToU q = new QToU(mQuestion.getId(),mUser.getId(), (mQuestion.getUserId() == mUser.getId())?1:0);
                try {
                    HttpUtils.post(postUrl, JSON.toJSONString(q), new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Looper.prepare();
                            if (response.code() != 200) {
                                Toast.makeText(getActivity(),"上传数据失败",Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getActivity(),"确认质疑成功",Toast.LENGTH_SHORT).show();
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Resources resources = getResources();
                                        Drawable drawable = resources.getDrawable(R.drawable.grey_bg);
                                        confirmButton.setEnabled(false);
                                        confirmButton.setBackground(drawable);
                                        confirmButton.setText("已确认");
                                    }
                                });
                            }
                            Looper.loop();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });



        //点击回答
        answerQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                View alertView = LayoutInflater.from(getActivity()).inflate(R.layout.alert_question, null);
                Button submitQuestion = alertView.findViewById(R.id.submit_question);
                EditText questionContent = alertView.findViewById(R.id.editTextTextMultiLine);
                AlertDialog dialog = builder.setTitle("回答质疑内容").setView(alertView).show();
                submitQuestion.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String url = "/user/submitAnswer";
                        Answer answer = new Answer(mQuestion.getId(),mUser.getName(),questionContent.getText().toString());
                        try {
                            HttpUtils.post(url, JSON.toJSONString(answer), new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {

                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    Looper.prepare();
                                    if (response.code() != 200) {
                                        Toast.makeText(getActivity(),"上传失败",Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(getActivity(),"回答成功",Toast.LENGTH_SHORT).show();
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                answerList.add(answer);
                                                mAdapter.notifyDataSetChanged();
                                                dialog.dismiss();
                                            }
                                        });
                                    }
                                    Looper.loop();

                                }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });


        return view;

    }

    //更新UI
    private void updateUI() throws IOException {
        questionContent.setText("质疑内容: " + mQuestion.getContent());
        String url = "/user/seeAnswer/"+mQuestion.getId();
        HttpUtils.get(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String str = response.body().string();
                if (response.code() != 200) {
                    Toast.makeText(getActivity(),"数据获取失败",Toast.LENGTH_SHORT).show();
                }else {
                    answerList = JSON.parseArray(str, Answer.class);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter = new OrderListAdapter();
                            mRecyclerView.setAdapter(mAdapter);
                        }
                    });
                }
                Looper.loop();
            }
        });
        String postUrl = "/user/checkPersonConfirm";
        QToU q = new QToU(mQuestion.getId(),mUser.getId(), (mQuestion.getUserId() == mUser.getId())?1:0);
        HttpUtils.post(postUrl, JSON.toJSONString(q), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String str = response.body().string();
                Log.d("Main", "onResponse: " + str);
                if (response.code() != 200) {
                    Toast.makeText(getActivity(),"数据故障",Toast.LENGTH_SHORT).show();
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //ui更新
                            if (str.equals("true")) {
                                Resources resources = getResources();
                                Drawable drawable = resources.getDrawable(R.drawable.grey_bg);
                                confirmButton.setEnabled(false);
                                confirmButton.setBackground(drawable);
                                confirmButton.setText("已确认");
                            }
                            //判断是否为班委
                            if (mUser.getIsClassCommittee() == 1) {
                                answerQuestion.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
                Looper.loop();
            }
        });
    }


    //adapter
    class OrderListAdapter extends RecyclerView.Adapter<OrderHolder> {

        @NonNull
        @Override
        public OrderHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new OrderHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(@NonNull OrderHolder holder, int position) {
            Answer answer = answerList.get(position);
            holder.setIsRecyclable(false);
            holder.bind(answer);
        }

        @Override
        public int getItemCount() {
            if (answerList == null) {
                return 0;
            }
            return answerList.size();
        }
    }

    class OrderHolder extends RecyclerView.ViewHolder {
        private Answer mAnswer;
        private TextView answerPerson, answerContent;

        public OrderHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_answer, parent, false));
//            itemView.setOnClickListener(this);
            //绑定
            answerPerson = itemView.findViewById(R.id.answer_person);
            answerContent = itemView.findViewById(R.id.answer_content);
        }

        public void bind(Answer answer) {
            mAnswer = answer;
            answerPerson.setText("回答人: "+mAnswer.getAnswerPerson());
            answerContent.setText("内容: "+mAnswer.getContent());
        }



    }
}